<template>
  <el-dialog
    title="新增文章"
    :visible="showDialog"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容" prop="articleBody">
        <quill-editor v-model="formData.articleBody"></quill-editor>
      </el-form-item>
      <el-form-item label="视频地址">
        <el-input v-model="formData.videoURL"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" style="text-align: right">
      <el-button @click="$emit('update:showDialog', false)">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add as addArticleApi, detail as getArticleDetailApi, update as editArticleApi } from '@/api/hmmm/articles.js'
export default {
  props: {
    // 控制对话框显示与隐藏
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 表单数据对象
      formData: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 表单校验规则
      formRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 监听对话框的关闭
    handleClose () {
      this.$emit('update:showDialog', false)
      this.$refs.formRef.resetFields()
      this.formData = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },
    // 表单的提交
    async submit () {
      try {
        await this.$refs.formRef.validate()
        if (this.formData.id) {
          // 编辑
          await editArticleApi(this.formData)
          this.$message.success('修改成功')
        } else {
          // 添加
          await addArticleApi(this.formData)
          this.$message.success('添加成功')
        }
        this.$emit('update:showDialog', false)
        this.$parent.getArticlesList()
      } catch (error) {
        console.log(error)
        this.$message.error('表单有误')
      }
    },
    // 获取文章详情
    async getArticleDetail (id) {
      const { data } = await getArticleDetailApi({ id })
      console.log(data)
      this.formData = data
    }
  }
}
</script>

<style scoped lang='scss'>
</style>
